import utils from '../../modules/utils'
import {sessionStore} from "../bianmaba-store"
import Vue from "vue";
import axios from 'axios'
import Login from "./Login";

//显示登录窗口函数
const login = function (url) {
  let exists = document.getElementById('login');
  if (!exists) {
    let LoginCmp = new Vue({
      template: '<login id="login" isPage="false" loginUrl="' + url + '"></login>', components: {Login}
    }).$mount();

    document.getElementById('app').appendChild(LoginCmp.$el)
    LoginCmp.$children.forEach(child => {
      if (child.$attrs.id == "login") {
        window.login = child;
      }
    })

  } else if (window.login.visible !== true) {
    window.login.visible = true;
  }
}

const BianmabaAuth = {
  install: function (Vue, options = {router: null, loginUrl: "oauth/token"}) {
    console.log("plugin:bianmaba-auth load...")
    if (utils.isEmpty(options.router)) {
      throw "Router option is required and cannot be empty.";
    }
    if (utils.isEmpty(options.loginUrl)) {
      throw "LoginUrl option is required and cannot be empty.";
    }

    //处理ajax请求认证，判断是否需要弹出登录窗口
    axios.interceptors.request.use(config => {
      let user = sessionStore.get("user");
      if (!utils.isEmpty(user) && user.hasOwnProperty("access_token") && user.access_token) {
        config.headers['Authorization'] = 'Bearer ' + user.access_token;
      } else {
        delete config.headers['Authorization']
      }
      return config
    }, error => {
      return Promise.reject(error)
    });
    axios.interceptors.response.use(
      response => {
        return response
      },
      error => {
        console.log(arguments)
        if (error.response.status == 401) {
          sessionStore.remove("user")
          if (sessionStore.get("request_queue") && sessionStore.get("request_queue").length > 0) {
            sessionStore.get("request_queue").push(error.config);
          } else {
            sessionStore.set("request_queue", [error.config])
          }
          login(options.loginUrl, Vue);
        }
        Vue.prototype.$message.error(error.response.data.result)
        return Promise.reject(error)
      }
    )

    Vue.$login = Vue.login = login;
  }
}


export default BianmabaAuth
